﻿    using System;
    using System.ComponentModel;
    using System.Net;
    using System.Net.Sockets;

    class SocketClient
    {
        /// <summary>
        /// 作者:WangJunLiang || Wechat:Joronwongx
        /// </summary>

        public delegate void ReceServiceData(byte[] Buf, int nBufLenght);
        public event ReceServiceData SendReceEnvent;

		public bool socketRunning = false;

        public struct SocketClientIP
        {
            public string strIpAddress;
            public int nPort;
        };

        #region 线程管理 监听服务器线程

        public Socket m_TcpClient = null;
        private BackgroundWorker m_ReceServiceBuf_BackgroundWorker = null;

        #endregion

        #region 监听服务

        //内容监听
        private void ReceServiceDataClick(object sender, DoWorkEventArgs e)
        {
            try
            {
                while (!m_ReceServiceBuf_BackgroundWorker.CancellationPending)
                {
                    if (m_TcpClient.Poll(10, SelectMode.SelectRead))
                    {
                        m_ReceServiceBuf_BackgroundWorker.CancelAsync();//停止执行DoWork
                        break;
                    }
                    byte[] buffer = new byte[4096];
                    int nReceBufCnt = m_TcpClient.Receive(buffer);
                    SendReceEnvent(buffer, nReceBufCnt);
                }
                 m_TcpClient.Shutdown(SocketShutdown.Both);
                 m_TcpClient.Close();
                 m_TcpClient = null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                //m_TcpClient.Close();
                //m_TcpClient = null;
            }
        }
        #endregion

        public bool isConnected()
        {
            if (m_TcpClient != null)
            {
                return m_TcpClient.Connected;
            }

            return false;
        }

        //创建连接
        public bool SocketConnect(SocketClientIP ClientIP)
        {
            try
            {
                if (m_TcpClient == null || m_TcpClient.Poll(10, SelectMode.SelectRead))
                {
                    //通过IP和端口号来定位一个所要连接的服务器端
                    m_TcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    m_TcpClient.Connect(new IPEndPoint(IPAddress.Parse(ClientIP.strIpAddress), ClientIP.nPort));

                    m_ReceServiceBuf_BackgroundWorker = new BackgroundWorker();
                    m_ReceServiceBuf_BackgroundWorker.DoWork += ReceServiceDataClick;
                    m_ReceServiceBuf_BackgroundWorker.WorkerSupportsCancellation = true; //允许取消
                    m_ReceServiceBuf_BackgroundWorker.RunWorkerAsync();//开始执行DoWork
                    return true;
                }
                return false;
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                m_TcpClient = null;
                return false;
            }
        }

        //断开连接
        public bool SocketBreak()
        {
            try
            {
                if (m_TcpClient != null && m_TcpClient.Connected)
                {
                    m_TcpClient.Shutdown(SocketShutdown.Both);
					m_TcpClient.Close();
					m_TcpClient = null;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }

        //发送内容
        public void SocketSend(byte[] buf)
        {
            try
            {
			if (m_TcpClient != null && m_TcpClient.Connected)
			{
				m_TcpClient.Send(buf);
				socketRunning = true;
			}
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
    }

